<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    DistributorController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    DistributorController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Admin_DistributorController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * The auth data
     * @var Zend_Auth
     */
    protected $_auth;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Set admin layout
        $this->_helper->layout()->setLayout('admin');

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $this->view->language = $locale->getLanguage();

        // Get language ID
        $languageModel = new Admin_Model_Language();
        $this->_languageId = $languageModel->findIdByShortCode($locale->getLanguage());

        // Chect authenctication
        $this->_auth = Zend_Auth::getInstance();
        if (!$this->_auth->hasIdentity()) {
            $this->_redirect('/' . $this->view->language . '/admin/login');
        }

        // Get current url without language
        $this->view->currentUrl = str_replace('/' . $locale->getLanguage(), '', $this->_request->getRequestUri());

        $this->view->shopName = Zend_Registry::get('config')->shopName;
    }

    /**
     * Action for index
     */
    public function indexAction()
    {
        // Check AJAX
        $isAjax = false;
        if ($this->getRequest()->isXmlHttpRequest()) {
            // If AJAX - turn of auto render
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $isAjax = true;
        }

        // Initialize filters for orders
        $id = null;
        $name = null;
        $manager = null;
        $email = null;
        $phone = null;
        $currencyId = null;
        $sort = null;
        $direction = null;
        $page = 1;
        $rowCount = 20;


        // Initialize form for filter
        $form = new Admin_Model_FormDistributors();
        $form->setAction('/' . $this->view->language . '/admin/distributor/index');

        // Get request params
        if ($this->getRequest()->isPost() && $form->isValid($data = $this->_request->getPost())) {
            $id = $data['id'];
            $name = $data['name'];
            $manager = $data['manager'];
            $email = $data['email'];
            $phone = $data['phone'];
            $currencyId = $data['currency'];
            $sort = $data['sort'];
            $direction = $data['direction'];
            $page = $data['page'];
            $rowCount = $data['rows'];
        }

        // Get distributors from database
        $distributorModel = new Admin_Model_Distributor();
        $this->view->distributors = $distributorModel->getAllByFilter($id, $name, $manager, $email, $phone, $currencyId, $sort, $direction, $page, $rowCount);

        // Get page count
        $recordsCount = $distributorModel->getCountByFilter($id, $name, $manager, $email, $phone, $currencyId, $sort, $direction, $page, $rowCount);
        $form->records_count->setValue($recordsCount);
        $form->pages_count->setValue(ceil($recordsCount / $rowCount));

        // Add form to view
        $this->view->formDistributors = $form;

        // Render AJAX content
        if ($isAjax) {
            echo $this->view->render('/distributor/_filtered.phtml');
        }

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Action for edit
     */
    public function editAction()
    {
        // Initialize distributor form
        $form = new Admin_Model_FormDistributor();
        $form->setAction('/' . $this->view->language . '/admin/distributor/save/');

        // Get id of distributor
        $id = $this->_request->getParam('id');
        if ($id) {
            // Prepare distributor for editing
            $distributorModel = new Admin_Model_Distributor();
            $distributor = $distributorModel->getById($id);
            if ($distributor) {
                $form->id->setValue($distributor->id);
                $form->name->setValue($distributor->name);
                $form->manager->setValue($distributor->manager);
                $form->email->setValue($distributor->email);
                $form->phone->setValue($distributor->phone);
                $form->currency->setValue($distributor->currency_id);
            }
        }
        $this->view->formDistributor = $form;

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Action for save
     */
    public function saveAction()
    {
        // Initialize distributor form
        $form = new Admin_Model_FormDistributor();
        $form->setAction('/' . $this->view->language . '/admin/distributor/save/');

        // Has the distributor form been posted?
        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getPost();

            // If the submitted data is valid, attempt to save distributor
            if ($form->isValid($data)) {
                $distributor = array();
                $distributor['id'] = $data['id'];
                $distributor['name'] = $data['name'];
                $distributor['manager'] = $data['manager'];
                $distributor['phone'] = $data['phone'];
                $distributor['email'] = $data['email'];
                $distributor['currency_id'] = $data['currency'];
                $distributorModel = new Admin_Model_Distributor();
                $distributorModel->save($distributor);
                $this->_redirect('/' . $this->view->language . '/admin/distributor/index');
            } else {
                $this->view->errors = $form->getErrors();
            }
        }
        $this->view->formDistributor = $form;
        $this->render('edit');

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

}

